package com.ashapo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.DataInputStream;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

/**
 * 测试文件操作类
 * @author Administrator
 */
public class Fso {
	
	public static void main(String[] args) throws IOException{ //规避IO错误
		//File fso = new File("H://金奖章客户端接口规范 V1.2.19.docx"); //正反斜杠都是支持的
		File fso = new File("H://");
		if(fso.exists()){
			System.out.println("FSO存在");
		}else{
			System.err.println("FSO不存在");
		}
		if(fso.isDirectory()){
			System.out.println("是目录");
		}else{
			System.err.println("不是目录");
		}
		if(fso.isFile()){
			System.out.println("是文件");
		}else{
			System.out.println("不是文件");
		}
		
		//循环不含子目录
		for (String arg : fso.list()) {
			System.out.println(arg);
		}
		
		//搜索txt文件的过滤器
		FilenameFilter fnfilter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(".txt");
			}
		};
		fso = new File("F:\\MyDo\\JAVA\\");
		for (String arg : fso.list(fnfilter)) {
			System.out.println(arg);
		}
		
		File fso2 = new File("F:\\MyDo\\JAVA\\gm_menu.sql");
		if(!fso2.exists()){
			fso2.createNewFile();
		}
		try (RandomAccessFile raf = new RandomAccessFile(fso2, "rw") //以随机字节方式访问文件
		) {
			System.out.println(raf.getFilePointer());
		}
		
		//以字节流方式访问
		FileInputStream in = new FileInputStream(fso2);
		int b;
		int i = 0;
		while((b = in.read()) != -1){
			StringBuilder sb = new StringBuilder(Integer.toHexString(b));
			if(b <= 0xf){
				sb.insert(0, "0");
			}
			sb.append(" ");
			System.out.print(sb.toString());
			if(i++ % 10 == 0){
				System.out.println("");
			}
		}
		in.close();
		
		System.out.println();
		long start_time = System.currentTimeMillis(); //当前时间
		System.out.println(start_time);
		
		//字节流
		FileInputStream fis = new FileInputStream("F:\\MyDo\\JAVA\\gm_menu.sql");
		
		//数据流
		DataInputStream dis = new DataInputStream(fis);
		
		//缓冲流，性能提升
		BufferedInputStream bis = new BufferedInputStream(fis);
		
		//输出流同样
		
		
		//字节流和字符流
		
		//默认编码是项目编码，在文件操作时最好手动确认编码问题
		
		//带缓冲读取流
		BufferedReader br = new BufferedReader(
				new FileReader("F:\\MyDo\\JAVA\\gm_menu.sql")
		);
		String line;
		while ((line = br.readLine()) != null) {		
			System.out.println(line);
		}
		br.close();
		
		BufferedWriter bw = new BufferedWriter(
				new FileWriter("F:\\MyDo\\JAVA\\gm_menu.sql")
		);
		bw.newLine();
		bw.write("这是新追加的一行哦");
		bw.close();
		
		PrintWriter pw = new PrintWriter("F:\\MyDo\\JAVA\\gm_menu.sql");
		pw.println("这是新追加的一行哦2");
		pw.close();
	}
}
